<?php
namespace app\admin\controller;
use think\Request;
use think\Db;

class User extends Common {

	private $db = null;
	private $config = '';
	private $default_config = '';
	private $oto_db_prefix = ''; //oto平台数据库名和表前缀
	private $pt_table_prefix = ''; //跑腿平台表前缀
	private $userField = '';
	protected function _initialize(){
		parent::_initialize();
		$this->config = config('database.db_config');
		$this->default_config = config('database');
		$this->oto_db_prefix = $this->config['database'].'.'.$this->config['prefix'];
		$this->pt_table_prefix = config('database.prefix');
		$this->db = Db::connect($this->config);
		$this->userField = array('u.userId','u.loginName','u.userName','u.userMoney','u.userType','u.createTime','u.userPhone','u.userStatus','u.isAudit');
	}
	
	//用户列表
	public function index(){
		$map = "u.userFlag = 1";
		$userPhone = input('get.userPhone');
		$loginName = input('get.loginName');
		$userType = input('get.userType',-1);
		if ($userPhone!='') {
			$map .=" and u.userPhone='{$userPhone}'";
		}
		if ($loginName!='') {
			$map .=" and u.loginName='{$loginName}'";
		}
		if ($userType!=-1) {
			$map .=" and u.userType='{$userType}'";
		}
		$params = array();
		if (!empty($_REQUEST)){
			$params = $_REQUEST;
			unset($params['page']);
		}
 		$data = $this->db->name('users as u')->where($map)->field($this->userField)
		->order('u.createTime desc')->paginate(config('page_size'), false, array('query' => $params));
		$this->assign('lists',$data);
		$this->assign('page',$data->render());
		$this->assign('userPhone',$userPhone);
		$this->assign('loginName',$loginName);
		$this->assign('userType',$userType);
		return $this->fetch();
	}

	/**
	 * [toEdit 前去会员修改页面]
	 * @return [type] [description]
	 */
	public function toEdit(){
		$id = intval(input('id',0));
		if ($id>0){
			// $this->error('操作失败');
			$data =  $this->db->name('users')->where(array('userId' => $id))->find();
			if (strpos($data['userPhoto'],"http://") === 0) {
				
			}else{
				$data['userPhoto'] =config('YAH_web').'/'.$data['userPhoto'];
			}
			// dump($data);
			$data['businessLicenseUrl'] =config('YAH_web').$data['businessLicenseUrl'];
			$data['idCardFrontUrl'] =config('YAH_web').$data['idCardFrontUrl'];
			$data['idCardVersoUrl'] =config('YAH_web').$data['idCardVersoUrl'];
			$data['handIdCardUrl'] =config('YAH_web').$data['handIdCardUrl'];
			// dump($data);
			if (empty($data)) $this->error('数据不存在');
			$this->assign('data',$data);
			return $this->fetch('edit');
		}else{
			return $this->fetch('add');
		}
	}

	/**
	  * 新增会员
	  */
	 public function addUser(){
	 	$userName = input('userName');
	 	$loginName = input('loginName');
	 	$userSex = input('userSex',0);
	 	$userPhone = input('userPhone');
	 	$userQQ = input('userQQ');
	 	$userStatus = input('userStatus',0);
	 	$userScore = input('userScore',0);
	 	$userTotalScore = input('userTotalScore',0);
	 	$userEmail = input('userEmail');
	 	$userType = input('userType',0);
	 	// $loginPwd = md5(input('loginPwd'));
	 	$userPhoto = input('user');
	 	// $data["loginName"] = I("loginName");
	 	$arr=range(0,9);
		shuffle($arr);
		$sjs=$arr[0].$arr[1].$arr[2].$arr[3];

		$loginPwd = trim(input('loginPwd'));

		$loginPwd=md5($loginPwd.$sjs);

	 	$data = [
	 		'userName'=>$userName,
	 		'loginPwd'=>$loginPwd,
	 		'loginSecret'=>$sjs,
	 		'userEmail'=>$userEmail,
	 		'userPhone'=>$userPhone,
	 		'loginName'=>$loginName,
	 		'userSex'=>$userSex,
	 		'userStatus'=>$userStatus,
	 		'userScore'=>$userScore,
	 		'userTotalScore'=>$userTotalScore,
	 		'userQQ'=>$userQQ,
	 		'userType'=>$userType,
	 		'userPhoto'=>$userPhoto,
	 		'userFlag'=>1,
	 		'createTime'=>date('Y-m-d H:i:s')
	 	];
	 	// dump($data);
	 	// exit();
	 	$upload_data = $this->user_upload();
		$data = array_merge($data,$upload_data);
	 	$m = $this->db->name('users');
	 	if ($m->where(array('userName' => $data['userName']))->find()) return json(array('code' => 0,'msg' => '用户名已存在'));
		if ($m->where(array('userPhone' => $data['userPhone']))->find()) return json(array('code' => 0,'msg' => '手机号码已存在'));
		if($m->insert($data)){
			$result = ['code'=>1,'msg'=>'新增成功'];
		}else{
			$result = ['code'=>0,'msg'=>'新增失败'];
		}
		return json($result);
	 }

	/**
	 * [edit 修改会员操作]
	 * @return [json] [ajax请求]
	 */
	public function edit(){
		$m = $this->db->name('users');
    	if(input('id/d')>0){
	    	$id = (int)input('post.id');
			$data["userScore"] = (int)input("post.userScore");
			$data["userTotalScore"] = (int)input("post.userTotalScore");
			$data["userName"] = input("post.userName");
			$data["userPhoto"] = input("post.userPhoto");
			$data["userSex"] = (int)input("post.userSex");
		    $data["userQQ"] = input("userQQ");
		    $data["userPhone"] = input("post.userPhone");
		    $data["userEmail"] = input("post.userEmail");
		    $upload_data = $this->user_upload();
		    $upload_data1 = $this->user_upload1();
		    $upload_data2 = $this->user_upload2();
		    $upload_data3 = $this->user_upload3();
		    $upload_data4 = $this->user_upload4();
			$data = array_merge($data,$upload_data,$upload_data1,$upload_data2,$upload_data3,$upload_data4);
			$rs = $m->where("userId=".$id)->update($data);
			if(false !== $rs){
				$rs = true;
			}
    	}else{
    		$rs = $m->addUser();//新增
    	}
    	if($rs){
			$result = array('code' => 1,'reload' => 1,'url' => url('User/index'),'msg' => '编辑成功');
		}else{
			$result = array('code' => 0,'reload' => 1,'url' => url('User/index'),'msg' => '编辑');
		}
		return json($result);
	}

	/**
	 * [user_upload 上传图片-头像
	 * @return [array] [description]
	 */
	private function user_upload(){
		$user_face = '';
		$userFace = request()->file('user_face');
		// 移动到框架应用根目录/public/uploads/ 目录下
		if ($userFace){
			$info = $userFace->move(ROOT_PATH . DS . config('uplaod') .DS.'face');
			if ($info){
				$user_face = config('uplaod').'/face/'.str_replace('\\', '/', $info->getSaveName());
			}else{
				$this->ajaxReturn(array('code' => 0,'msg' => '上传失败'));
			}
		}
		$current_img_url =  'http://'.$_SERVER['HTTP_HOST'].'/'.$user_face;
		$post_data = array();
		$post_data['imgUrl'] = $current_img_url;
		$rs = $this->post(config('YAH_web_upload'),$post_data);
		$data['userPhoto'] = '/'.$rs['imgUrl'];
		return $data;
	}

	/**
	 * [user_upload 上传图片-营业执照
	 * @return [array] [description]
	 */
	private function user_upload1(){
		$user_businessLicenseUrl = '';
		$user_businessLicense = request()->file('user_businessLicenseUrl');
		// 移动到框架应用根目录/public/uploads/ 目录下
		if ($user_businessLicense){
			$info = $user_businessLicense->move(ROOT_PATH . DS . config('uplaod') .DS.'idcard');
			if ($info){
				$user_businessLicenseUrl = config('uplaod').'/idcard/'.str_replace('\\', '/', $info->getSaveName());
			}else{
				$this->ajaxReturn(array('code' => 0,'msg' => '上传失败'));
			}
		}
		$current_img_url =  'http://'.$_SERVER['HTTP_HOST'].'/'.$user_businessLicenseUrl;
		$post_data = array();
		$post_data['imgUrl'] = $current_img_url;
		$rs = $this->post(config('YAH_web_upload'),$post_data);
		$data['businessLicenseUrl'] = '/'.$rs['imgUrl'];
		return $data;
	}

	/**
	 * [user_upload 上传图片-身份证正面照
	 * @return [array] [description]
	 */
	private function user_upload2(){
		$user_idCardFrontUrl = '';
		$user_idCardFront = request()->file('user_idCardFrontUrl');
		// 移动到框架应用根目录/public/uploads/ 目录下
		if ($user_idCardFront){
			$info = $user_idCardFront->move(ROOT_PATH . DS . config('uplaod') .DS.'idcard');
			if ($info){
				$user_idCardFrontUrl = config('uplaod').'/idcard/'.str_replace('\\', '/', $info->getSaveName());
			}else{
				$this->ajaxReturn(array('code' => 0,'msg' => '上传失败'));
			}
		}
		$current_img_url =  'http://'.$_SERVER['HTTP_HOST'].'/'.$user_idCardFrontUrl;
		$post_data = array();
		$post_data['imgUrl'] = $current_img_url;
		$rs = $this->post(config('YAH_web_upload'),$post_data);
		$data['idCardFrontUrl'] = '/'.$rs['imgUrl'];
		return $data;
	}

	 // 根据URL 和 参数发post请求
    private function post($url,$parameter){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($parameter));
        $result = curl_exec($ch);
        curl_close($ch);
        // print_r($result);
        $result = json_decode(trim($result,chr(239).chr(187).chr(191)),true);
        return $result;
        // $result = json_decode(trim($result,chr(239).chr(187).chr(191)),true);
    }

	/**
	 * [user_upload 上传图片-身份证反面照
	 * @return [array] [description]
	 */
	private function user_upload3(){
		$user_idCardVersoUrl = '';
		$user_idCardVerso = request()->file('user_idCardVersoUrl');
		// 移动到框架应用根目录/public/uploads/ 目录下
		if ($user_idCardVerso){
			$info = $user_idCardVerso->move(ROOT_PATH . DS . config('uplaod') .DS.'idcard');
			if ($info){
				$user_idCardVersoUrl = config('uplaod').'/idcard/'.str_replace('\\', '/', $info->getSaveName());
			}else{
				$this->ajaxReturn(array('code' => 0,'msg' => '上传失败'));
			}
		}
		$current_img_url =  'http://'.$_SERVER['HTTP_HOST'].'/'.$user_idCardVersoUrl;
		$post_data = array();
		$post_data['imgUrl'] = $current_img_url;
		$rs = $this->post(config('YAH_web_upload'),$post_data);
		$data['idCardVersoUrl'] = '/'.$rs['imgUrl'];
		return $data;
	}

	/**
	 * [user_upload 上传图片-手持身份证正面照
	 * @return [array] [description]
	 */
	private function user_upload4(){
		$user_handIdCardUrl = '';
		$user_handIdCard = request()->file('user_handIdCardUrl');
		// 移动到框架应用根目录/public/uploads/ 目录下
		if ($user_handIdCard){
			$info = $user_handIdCard->move(ROOT_PATH . DS . config('uplaod') .DS.'idcard');
			if ($info){
				$user_handIdCardUrl = config('uplaod').'/idcard/'.str_replace('\\', '/', $info->getSaveName());
			}else{
				$this->ajaxReturn(array('code' => 0,'msg' => '上传失败'));
			}
		}
		$current_img_url =  'http://'.$_SERVER['HTTP_HOST'].'/'.$user_handIdCardUrl;
		$post_data = array();
		$post_data['imgUrl'] = $current_img_url;
		$rs = $this->post(config('YAH_web_upload'),$post_data);
		$data['handIdCardUrl'] = '/'.$rs['imgUrl'];
		return $data;
	}

	public function editMoney(){
		$id = input('userId');
		$item = $this->db->name('users')->where('userId='.$id)->find();
		if($this->request->isPost()){
			$money = (float)input('userMoney');
	        $userType = intval(input('userType'));
	        $userId = intval(input('userId'));
	        $addMoney = (float)input('addMoney');
	        $reduceMoney = (float)input('reduceMoney');
	        $data = [];
	        if(!empty($addMoney))
	        {
	            $sum = round($addMoney,2);
	            $data['userMoney'] = round($money + $addMoney,2);
	        }

	        if(!empty($reduceMoney))
	        {
	            $sum = round($reduceMoney,2);
	            if($money>=$reduceMoney){
	            	$data['userMoney'] = round($money - $reduceMoney,2);
	            }
	        }

	        if( $this->db->name('users')->where(['userType'=>$userType,'userId'=>$userId])->update($data))
	        {
	            return $this->redirect('user/index');
	        }else{
	            return $this->redirect('user/index');
	        }			
		}
		$this->assign('item',$item);
		return $this->fetch('money');
	}



	/**
	 * [del 删除会员]
	 * @return [json] [description]
	 */
	public function del(){
		$m = $this->db->name('users');
		$id = input('id/d');
		if($m->where(['userId'=>$id])->delete()){
			$result = ['status'=>1,'msg'=>'删除成功','id'=>$id];
		}else{
			$result = ['status'=>0,'msg'=>'删除失败'];
		}
		return json($result);
	}

	/**
	 * [toggleStatus 切换会员状态]
	 * @return [json ] [description]
	 */
	public function toggleUserStatus(){
		$id = input('id');
		$userStatus = input('status');
		if($userStatus==0){
			$state = 1;
			$msg = '启用';
		}else{
			$state = 0;
			$msg = '停用';
		}
		$data = ['userStatus'=>$state];
		if($id>0){
			$res = $this->db->name('users')->where('userId='.$id)->update($data);
			if($res){
				$result = ['status'=>1,'msg'=>$msg.'成功','id'=>$id,'state'=>$state];
			}else{
				$result = ['status'=>0,'msg'=>'编辑失败'];
			}
		}else{
			$result = ['status'=>0,'msg'=>'没有找到'];
		}
		return json($result);
	}

	/**********************************************************************************************
	  *                                             账号管理                                                                                                                              *
	  **********************************************************************************************/
	/**
	 * [queryAccountByPage 账户列表]
	 * @return [type] [description]
	 */
    public function queryAccountByPage(){
    	$m = model('user');
    	$listobj = $m->queryAccountByPage();
    	$list = $listobj->toArray();
    	$pager = $listobj->render();
    	$list['page'] = $pager;
    	$this->assign('loginName',input('loginName'));
    	$this->assign('userStatus',input('userStatus',-1));
    	$this->assign('userType',input('userType',-1));
    	$this->assign('list',$list);
        return $this->fetch("account_list");
	}
	
	/**
	 * [toggleStatus 切换账户状态]
	 * @return [json ] [description]
	 */
	public function toggleStatus(){
		$id = input('id');
		$userStatus = input('status');
		if($userStatus==0){
			$state = 1;
			$msg = '启用';
		}else{
			$state = 0;
			$msg = '停用';
		}
		$data = ['userStatus'=>$state];
		if($id>0){
			$res = $this->db->name('users')->where('userId='.$id)->update($data);
			if($res){
				$result = ['status'=>1,'msg'=>$msg.'成功','id'=>$id,'state'=>$state];
			}else{
				$result = ['status'=>0,'msg'=>'编辑失败'];
			}
		}else{
			$result = ['status'=>0,'msg'=>'没有找到'];
		}
		return json($result);
	}

	/**
	 * [editAccount 修改账户信息]
	 * @return [json ] [description]
	 */
	public function editAccount(){
		$m = $this->db->name('users');
		$id = input('id');
		$userStatus = input('userStatus');
		$loginPwd = input('loginPwd');
		$payPwd = input('payPwd');
		if(!empty($loginPwd)){
			$data['loginPwd'] = md5($loginPwd);
		}
		if(isset($userStatus)&&input('userStatus')!=''){
			$data['userStatus'] = $userStatus;
		}
		if(!empty($loginPwd)){
			$data['payPwd'] = md5($payPwd);
		}
		if($id>0){
			$res = $m->where('userId='.$id)->update($data);
			if($res){
				$result = ['status'=>1,'msg'=>'修改成功'];
			}else{
				$result = ['status'=>0,'msg'=>'修改失败'];
			}
		}else{
			$result = ['status'=>0,'msg'=>'没有找到'];
		}
		return json($result);
	}

	// 用户账单流水
	public function water(){
		$map = "r.userid > 0";
		$map2 = "type = 3 ";
		$map3 = "type = 6 ";
		$startDate = input('startDate');
		$endDate = input('endDate');
		$userPhone = input('userPhone');
		$payWay = input('payWay',-1);
		$type = input('type',-1);
		if ($userPhone!='') {
			$map .=" and u.userPhone='{$userPhone}'";
		}
		
		if ($type!=-1) {
			$map .=" and r.type='{$type}'";
		}

		if ($payWay!=-1) {
			$map .=" and r.payWay='{$payWay}'";
		}

		
		if ($startDate !='' && $endDate == '') {
			$startime = strtotime($startDate.' 00:00:00');
			$map .=" and r.time >= {$startime}";
			$map2 .=" and time >= {$startime}";
			$map3 .=" and time >= {$startime}";

		}
		if ($startDate =='' && $endDate != '') {
			$endtime = strtotime($endDate.' 23:59:59');
			$map .=" and r.time <= {$endtime}";
			$map2 .=" and time <= {$endtime}";
			$map3 .=" and time <= {$endtime}";
		}
		if ($startDate !='' && $endDate != '') {
			$startime = strtotime($startDate.' 00:00:00');
			$endtime = strtotime($endDate.' 23:59:59');
			$map .=" and r.time <= {$endtime} and r.time >= {$startime}";
			$map2 .=" and time <= {$endtime} and time >= {$startime}";
			$map3 .=" and time <= {$endtime} and time >= {$startime}";
		}

		$params = array();
		if (!empty($_REQUEST)){
			$params = $_REQUEST;
			unset($params['page']);
		}
 		$data = $this->db->name('money_record as r')->field('r.*,u.userName,u.userPhone')->join("users u",'r.userid=u.userId')->where($map)->order('time desc')->paginate(config('page_size'), false, array('query' => $params));
 		// 历史充值总额
 		$history_total_recharge = $this->db->name('money_record')->where('type = 3')->sum('money');
 		// 当前时间区间充值总额
 		$current_total_recharge = $this->db->name('money_record')->where($map2)->sum('money');
 		// 历史消费总额
 		$history_total_expend = $this->db->name('money_record')->where('type = 6')->sum('money');
 		// 当前时间区间消费总额
 		$current_total_expend = $this->db->name('money_record')->where($map3)->sum('money');
		$this->assign('lists',$data);
		$this->assign('page',$data->render());
		$this->assign('startDate',$startDate);
		$this->assign('endDate',$endDate);
		$this->assign('userPhone',$userPhone);
		$this->assign('type',$type);
		$this->assign('payWay',$payWay);
		$this->assign('history_total_recharge',$history_total_recharge);
		$this->assign('history_total_expend',$history_total_expend);
		$this->assign('current_total_recharge',$current_total_recharge);
		$this->assign('current_total_expend',$current_total_expend);
		return $this->fetch();

	}

	public function audit(){
		$userId = input('id');
		$A = $this->db->name('users')->where(array('userId'=>$userId))->setField('isAudit', 1);
		if ($A !==false) {
			return json(['status'=>1,'msg'=>'审核成功']);
		}else{
			return json(['status'=>-1,'msg'=>'审核失败']);
		}
	}
	public function refund(){
		$userId = input('id');
		$A = $this->db->name('users')->where(array('userId'=>$userId))->setField('isAudit', -2);
		if ($A !==false) {
			return json(['status'=>1,'msg'=>'操作成功']);
		}else{
			return json(['status'=>-1,'msg'=>'操作失败']);
		}
	}
	
}